#!/usr/bin/env python3
import markdown
from docx import Document
from docx.shared import Pt, RGBColor, Inches
import os
import re
import sys

def convert_md_to_docx(md_file_path, output_file_path=None):
    """
    Convert a Markdown file to a Word document
    """
    if not output_file_path:
        # Use the same name but with .docx extension
        output_file_path = os.path.splitext(md_file_path)[0] + '.docx'
    
    # Read the markdown file
    with open(md_file_path, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    # Convert markdown to HTML
    html_content = markdown.markdown(
        md_content, 
        extensions=['tables', 'fenced_code']
    )
    
    # Create a new document
    doc = Document()
    
    # Process the HTML content
    # This is a very simplified approach - we're just handling some basic elements
    
    # Split the HTML into paragraphs
    paragraphs = re.split(r'<p>|</p>|<h1>|</h1>|<h2>|</h2>|<h3>|</h3>|<h4>|</h4>|<li>|</li>', html_content)
    
    # Process each paragraph
    for p in paragraphs:
        if p.strip():
            # Remove HTML tags (simplified approach)
            p = re.sub(r'<.*?>', '', p)
            # Add paragraph to document
            doc.add_paragraph(p.strip())
    
    # Save the document
    doc.save(output_file_path)
    
    return output_file_path

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python md_to_word.py <markdown_file> [output_docx_file]")
        sys.exit(1)
    
    md_file = sys.argv[1]
    
    if len(sys.argv) > 2:
        docx_file = sys.argv[2]
    else:
        docx_file = None
    
    output_path = convert_md_to_docx(md_file, docx_file)
    print(f"Conversion completed. Word document saved as: {output_path}") 